<template>
	<view>
		<view @click="click">
			<slot></slot>
		</view>
		<u-picker :show="show" ref="uPicker" :columns="calcList" :keyName="keyName"
			:closeOnClickOverlay="closeOnClickOverlay" @cancel="onCancel" @confirm="onConfirm" :defaultIndex="calcIndex"
			@change="changeHandler" :immediateChange="true" @close="onClose"></u-picker>
	</view>
</template>

<script>
	export default {
		name: "cg-picker",

		props: {
			keyName: {
				default: 'name',
				type: String
			},
			valueName: {
				default: 'id',
				type: String
			},
			value: {
				default: () => {
					return {}
				},
				type: Object | String
			},
			title: {
				default: '标题',
				type: String
			},

			/* 
			 [{
				 name: '',
				 id: 12,
				 children: [], //多级联动
			 }]
			 
			 */
			list: {
				default: () => {
					return []
				},
				type: Array
			},

			defaultIndex: {
				default: () => {
					return []
				},
				type: Array
			},
			closeOnClickOverlay: {
				default: false,
				type: Boolean
			},
			disabled: {
				default: false,
				type: Boolean
			}

		},
		created() {
			this.setList(this.list);
			this.calcList = this.middleList;
			uni.$on('homeRefresh',() => {
				this.onClose()
			})
		},
		beforeDestroy() {
			uni.$off('homeRefresh')
		},
		watch: {
			list: {
				deep: true,
				handler(res) {
					// console.error('res',res);
					if(!this.watchList) return
					this.setList(res);
					// #ifdef MP-WEIXIN
					this.calcList = this.middleList;
					
					// #endif
					// #ifndef MP-WEIXIN
					/* 直接赋值无法触发u-picker里的watch，改为深拷贝 */
					this.calcList = JSON.parse(JSON.stringify(this.middleList));
					// #endif
					
					this.watchList = false;
					
					if (!this.value[this.valueName]) return
					this.getDeepIndex(this.list, 0);
					this.calcIndex = this.middleIndex;
					// console.log('this.middleIndex', this.middleIndex);
					// this.calcIndex = [res.findIndex(item => item[this.valueName] == this.value[this.valueName])]
				}
			},
			value(e) {
				if(!this.watchVal) return
				this.watchVal = false;
				if (!this.list?.length) return
				this.getDeepIndex(this.list, 0);
				this.calcIndex = this.middleIndex;
				// console.log('this.middleIndex', this.middleIndex);
				// this.calcIndex = [this.list.findIndex(item => item[this.valueName] == this.value[this.valueName])]
			},
			defaultIndex(e) {
				this.calcIndex = e;
			}
		},
		data() {
			return {
				show: false,
				calcIndex: [0, 0],
				calcList: [
					[],
					[],
					[]
				],
				middleList: [],
				levelDeep: 1,
				middleIndex: [],
				watchVal: true,
				watchList: true
			};
		},
		methods: {
			getDeepIndex(list, parIndex) {
				list.forEach((item, index) => {
					if (item[this.valueName] == this.value[this.valueName]) {

						this.middleIndex[parIndex] = index;
					}
					if (item.children) {
						this.middleIndex[parIndex] = index;
						this.getDeepIndex(item.children, parIndex + 1)
					}
				})
			},
			onClose(e){
				this.show = false;
				this.$emit('close', e)
			},
			onCancel(e) {
				this.show = false;
				this.$emit('cancel', e)
			},
			onConfirm(e) {
				this.show = false

				const res = []
				e.values.forEach((item, index) => {
					res.push(item[e.indexs[index]])
				})



				// 一级的时候，返回对象，多层级的时候，返回最后一级对象+allRes
				if (this.levelDeep === 1) {
					this.$emit('confirm', res[0]);
					this.$emit('input', res[0]);
				} else {
					const response = JSON.parse(JSON.stringify(res[res.length - 1]));
					response.allRes = res;
					response.allText = res.map(item => item[this.keyName]).join('')

					this.$emit('input', response);
					this.$emit('confirm', response);
				}
				

			},
			click() {
				if (this.disabled) return
				this.show = true;
			},
			setList(list, parentIndex) {

				parentIndex = parentIndex || 0;
				this.middleList[parentIndex] = list;
				list.forEach((item, index) => {
					// console.log('111111111', 111111111, item.children);

					if (index === parentIndex && item.children?.length) {
						this.levelDeep++
						// console.log('99999999999', 99999999999,item);
						this.middleList[parentIndex + 1] = JSON.parse(JSON.stringify(item.children));
						this.setList(item.children, parentIndex + 1);
						console.warn(this.middleList)
					}
				})
				// return
				// this.calcList = [JSON.parse(JSON.stringify(this.list))]


			},
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e;
				// if (columnIndex === 0) {
				console.log('values',
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index);
				// picker为选择器this实例，变化第二列对应的选项
				if (values[columnIndex][index].children) {

					const data = JSON.parse(JSON.stringify(values[columnIndex][index].children))
					console.log('data', data);
					picker.setColumnValues(columnIndex + 1, data)
				}
				// }
				// if (columnIndex === 1) {
				// 	console.log('values', values);
				// 	// picker为选择器this实例，变化第二列对应的选项
				// 	if (values[1][index].children) {
				// 		const data = JSON.parse(JSON.stringify(values[1][index].children))
				// 		picker.setColumnValues(2, data)
				// 	}
				// }
			}
		}
	}
</script>

<style lang="scss">

</style>